package com.domainchen.framework.common.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author domainchen or cytxiamen@163.com
 * @version 创建时间：2016年3月11日 上午11:31:10
 * @类说明 流操作工具类
 */
public class StreamUtil {

	private static final Logger logger = LoggerFactory.getLogger(StreamUtil.class);

	public static String getString(InputStream is) {
		StringBuffer strBuffer = new StringBuffer();
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(is));
			String line = "";
			while ((line = reader.readLine()) != null) {
				strBuffer.append(line);
			}
		} catch (Exception e) {
			logger.error(" get String failure", e);
			throw new RuntimeException(e);
		}
		return strBuffer.toString();
	}

	/**
	 * 将输入流复制到输出流
	 * 
	 * @param inputStream
	 * @param outPutStream
	 */
	public static void copyStream(InputStream inputStream, OutputStream outPutStream) {
		try {
			int length = 0;
			byte[] buffer = new byte[4 * 1024];
			while ((length = inputStream.read(buffer, 0, buffer.length)) != -1) {
				outPutStream.write(buffer, 0, length);

			}
			outPutStream.flush();
		} catch (Exception e) {
			logger.error("copy stream failure", e);
			throw new RuntimeException(e);
		} finally {
			try {
				inputStream.close();
				outPutStream.close();
			} catch (Exception e2) {
				logger.error("close stream failure", e2);
			}
		}
	}
}
